package com.hnas.core.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {
	private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
	public static MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
	static {
		manager.getParams().setDefaultMaxConnectionsPerHost(50);
		manager.getParams().setMaxTotalConnections(100);
		manager.getParams().setConnectionTimeout(30000);
		manager.getParams().setSoTimeout(60000);
	}

	public static String request(HttpPara para) throws Exception {
		HttpClient client = new HttpClient(HttpUtil.manager);
		client.getHostConfiguration().setHost(para.getServerIp(),
				para.getServerport());
		client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
				"UTF-8");// UTF-8
		PostMethod post = new PostMethod(para.getUrl());
//		post.addRequestHeader("Content-Type", "text/html; charset=UTF-8");  
//		InputStream inputStream =null;
//		InputStreamReader ir = null;
//		BufferedReader br = null;
		try {
			// 登录
			int n = 0;
			NameValuePair[] paras = new NameValuePair[para.getParas().size()];
			for (Entry entry : para.getParas().entrySet())
				paras[n++] = new NameValuePair(String.valueOf(entry.getKey()),
						String.valueOf(entry.getValue()));
			post.setRequestBody(paras);
			int status = client.executeMethod(post);
			// String result = new
			// String(post.getResponseBody(),"UTF-8");//post.getResponseBodyAsString();
			// System.out.println( result);
			// 读取返回结果
//			inputStream = post.getResponseBodyAsStream();
//			ir = new InputStreamReader(inputStream);
//			br = new BufferedReader(ir);
//			StringBuffer stringBuffer = new StringBuffer();
//			String line;
//			while ((line = br.readLine()) != null) {
//				stringBuffer.append(line);
//			}
			InputStream in =post.getResponseBodyAsStream();
			String result = IOUtils.toString(in, "UTF-8");
//			String result = new String(post.getResponseBody(),"UTF-8");
			
			
//			String s = new String(stringBuffer,"UTF-8")

//			System.out.println(stringBuffer);

			log.debug("HTTP 调用"+para.getUrl()+"返回："+result);
			return result;//stringBuffer.toString();

			// return result;

		} catch (java.net.SocketTimeoutException e) {
			throw new Exception("发送指令超时！");
		} catch (IOException ex) {
			throw new Exception("指令发送出现网络故障！");

		} finally {
			// System.out.println(post.getResponseBodyAsString());
			post.releaseConnection();
			//关闭流
//			if (null!=br)
//			try {
//				br.close();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			if (null!=ir)
//			try {
//				ir.close();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			if (null!=inputStream)
//			try {
//				inputStream.close();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		}
		// return null;
	}
	public static String request2(HttpPara para) throws Exception {
		URL url = new URL(para.formUrl());
		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
		urlConnection.setConnectTimeout(15000);
		urlConnection.setReadTimeout(60000);
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection
            .getInputStream()));
//        inputLine = in.readLine().toString();
		String data = null;
		StringBuffer sb = new StringBuffer();
		while ((data = in.readLine()) != null) {
			sb.append(data);
		}
		return sb.toString();
		
	}
}